package com.ktwlsoft.fundmanage.fundFlow.processHandler.FundOutServiceTask;

import java.util.Date;

import com.ktwlsoft.fundmanage.domain.entity.FundInRecord;
import com.ktwlsoft.fundmanage.domain.entity.FundSuperviseAccept;
import com.ktwlsoft.fundmanage.domain.entity.TransferApply;
import com.ktwlsoft.fundmanage.fundFlow.processHandler.BaseServiceTask;
import com.ktwlsoft.fundmanage.payload.IAccountUser;
import com.ktwlsoft.fundmanage.payload.fundOut.FundOutOrCancelRequest;
import com.ktwlsoft.fundmanage.utils.UserUtils;

import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Service;

@Service
public class CancelApply extends BaseServiceTask {

    @Override
    public void execute(DelegateExecution execution) {
        long transId = (Long) execution.getVariable("transId");
        FundOutOrCancelRequest fundOutOrCancelRequest = (FundOutOrCancelRequest) execution
                .getVariable("fundOutOrCancelRequest");
        IAccountUser user = UserUtils.getUser();
        //设置划款单未撤销，并把撤销人加上
        TransferApply apply = fundOutService.findTransferApply(transId);
        apply.cancel(user.getName(), user.getUserId(), new Date());
        apply.setCancelRemark(fundOutOrCancelRequest.getRemark());

        FundInRecord fundInRecord = fundInService.findFundInResult(apply.getFundInCode());
        fundInRecord.setHasTransfer(fundInRecord.getHasTransfer().subtract(apply.getAmount()));
        fundInRecord.setTransferd(false);
        //把资金录入恢复，但是如果是开具第三方划款单的，要保持原来的已划款状态
        //        if (apply.getTransferType() == TransferApply.TransferType.THIRD) {
        //            fundInRecord.setTransferd(true);
        //        } else if (apply.getTransferType() == TransferApply.TransferType.SPECIAL) {
        //            if (fundOutService.getTransferApplyRepository()
        //                    .existsByTransferTypeAndApprovalFlow(TransferApply.TransferType.THIRD, apply.getApprovalFlow())) {
        //                fundInRecord.setTransferd(true);
        //            }
        //        } else {
        //            fundInRecord.setTransferd(false);
        //        }

        //恢复案件状态
        FundSuperviseAccept fundSuperviseAccept = fundInService.findBusinessByTsCode(apply.getTsCode());
        fundSuperviseAccept.setAmountLeft(fundSuperviseAccept.getAmountLeft().add(apply.getAmount()));
        if (apply.getTransferType() == TransferApply.TransferType.REFUND) {
            fundSuperviseAccept.setRefundState(FundSuperviseAccept.RefundState.CANCEL);
        }
    }
}
